package com.freeman.cement.config;

import com.freeman.cement.system.BllFrame;
import com.freeman.cement.entity.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class UserActivityAspect {
    private static final Logger logger = LoggerFactory.getLogger(UserActivityAspect.class);

    @Before("execution(* com.freeman.cement.controller.*.*(..)) && !execution(* com.freeman.cement.controller.LoginController.login(..))")
    public void updateUserActivity(JoinPoint joinPoint) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                String token = request.getHeader("token");
                if (token != null) {
                    logger.debug("收到请求，token: {}", token);
                    // 更新所有匹配token的用户的最后活动时间
                    boolean updated = false;
                    for (User user : BllFrame.loginUsrsCache.values()) {
                        if (token.equals(user.getToken())) {
                            user.setLastActiveTime(new Date());
                            updated = true;
                            logger.debug("更新用户[{}]的最后活动时间", user.getUsername());
                        }
                    }
                    if (!updated) {
                        logger.warn("未找到匹配token的用户，token: {}", token);
                    }
                } else {
                    logger.debug("请求中没有token");
                }
            }
        } catch (Exception e) {
            logger.error("更新用户活动时间时发生错误", e);
        }
    }
} 